<template>
    <div>
        <!-- 面包屑导航 -->
       <el-breadcrumb separator-class="el-icon-arrow-right">
       <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
       <el-breadcrumb-item>商品管理</el-breadcrumb-item>
       <el-breadcrumb-item>商品列表</el-breadcrumb-item>
       </el-breadcrumb>

       <!-- card视图 -->
        <el-card>
            <!-- 添加按钮 -->
            <el-row>
                <el-col>
                      <el-button type="primary" class="cateBtn" @click="classifyBtn">添加分类</el-button>
                </el-col>
            </el-row>


            <!-- 树形表单 -->
            <tree-table :data='catelist' :columns='columns' show-index :selection-type='false' :expand-type='false' border>
                 <template slot="isok" slot-scope="scope">
                     <i class="el-icon-success" v-if="scope.row.cat_deleted ===false" style="color:lightgreen"></i>
                     <i class="el-icon-error" v-else style="color:res"></i>
                 </template>
                 <template slot="order" slot-scope="scope">
                     <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
                     <el-tag v-else-if="scope.row.cat_level===1" type="success">二级</el-tag>
                     <el-tag v-else type="danger">三级</el-tag>
                 </template>
                 <template slot-scope="scope" slot="opt">
                     <el-button type="primary" size="mini"  icon="el-icon-edit" @click="editCatePop(scope.row.cat_id)">编辑</el-button>
                     <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteCataPop(scope.row.cat_id)">删除</el-button>
                 </template>
            </tree-table>


            <!-- 分页功能 -->
            <el-pagination  @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="querInfo.pagenum"
            :page-sizes="[5, 10, 15, 20]"  :page-size="100"  layout="total, sizes, prev, pager, next, jumper"  :total="this.total">
            </el-pagination>


            <!-- 添加分类弹框 -->
            <el-dialog  title="提示" :visible.sync="classifyPop" width="50%" @close='addCateClose'>
                <el-form ref="classifyRef" :model="classifyForm" label-width="100px" :rules="classifyRules">
                <el-form-item label="分类名称：" prop="cat_name">
                <el-input v-model="classifyForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="父级分类：">  
                    <!-- options：用来指定数据源 -->
                    <!-- props：用来指定配置对象 -->
                <el-cascader expand-trigger='hover'  v-model="cascade" :options="parentCateList" :props="casCaderProps" 
                @change="parentCateChange" clearable change-on-select>
                </el-cascader>  
                </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                <el-button @click="classifyPop = false">取 消</el-button>
                <el-button type="primary" @click="addCate">确 定</el-button>
                </span>
            </el-dialog> 


            <!-- 点击编辑按钮弹框 -->
            <el-dialog  title="提示" :visible.sync="editCateVisible" width="50%" >
                <el-form :model="editCateForm" :rules="editCateRules" ref="editCateRef" label-width="100px">
                <el-form-item label="分类名称" prop="cat_name">
                <el-input v-model="editCateForm.cat_name"></el-input>
                </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                <el-button @click="editCateVisible = false">取 消</el-button>
                <el-button type="primary" @click="daaEditPop">确 定</el-button>
                </span>
            </el-dialog>



        </el-card>
    </div>
</template>

<script>
export default {
    data(){
        return{
            // 商品分类的数据列表
            catelist:[],
            // 查询条件
            querInfo:{
                type:3,
                pagenum:1,
                pagesize:5
            },
            // 总数据条数
            total:0,
            // 为table指定列的定义
            columns:[
                {
                    label:'分类名称',
                    prop:'cat_name'                
                },
                {
                    label:'是否有效',
                    type:'template',
                    template:'isok'
                },
                {
                    label:'排序',
                    type:'template',
                    template:'order'
                },
                {
                    label:'操作',
                    type:'template',
                    template:'opt'
                }
             ],
            //  分类按钮
            classifyPop:false,
            classifyForm:{
                cat_name:'',
                // 父分类的ID
                cat_pid:0,
                // 父类的等级 默认要添加的是一级分类
                cat_level:0
            },
            //  验证
           classifyRules:{
               cat_name :[
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
               ]
           },
            //  获取父级的分类列表
             parentCateList:[],

            //  选中的父级分类的ID数组
            cascade:[],
            // 指定级联选择器的配置对象
            casCaderProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },

            // 编辑按钮弹框
            editCateVisible:false,
            editCateForm:{
                cat_name:'',
                cat_id:''
            },
            editCateRules:{
                cat_name:[
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' } 
                ]
            }




        }
    },
    // 生命周期
    created(){
        this.getCateList()
    },
    methods:{
        //  获取商品列表
       async getCateList(){
          const {data:res} = await this.$http.get('categories',{params:this.querInfo})
           if(res.meta.status !==200){
               return this.$message.error('获取商品列表错误！')
           }
           this.catelist = res.data.result
           this.total = res.data.total          
        },


        //  监听pageSize 
        handleSizeChange(newSize){
            this.querInfo.pagesize = newSize
            this.getCateList()
        },
        handleCurrentChange(newSize){
            this.querInfo.pagenum = newSize
            this.getCateList()
        },


        // 分类弹框
        classifyBtn(){
            // 先获取父级的分类列表
            this.getParentCateList()
            // 在弹出提示框
            this.classifyPop=true
        },

        //  获取父级的分类列表
        async getParentCateList(){
             const {data:res} = await this.$http.get('categories',{params:{type:2}})       
                if(res.meta.status !==200){
                    return this.$message.error('获取父级列表分类失败！')
                }
                 this.parentCateList = res.data         
        },

        // 级联框改变事件
        parentCateChange(){
            // 如果 cascade 数组中的length 大于0 证明选中的父级分类
            // 反之，就说明没有选中父级关系
            if(this.cascade.length > 0) {
                //  父级分类的id
                this.classifyForm.cat_pid = this.cascade[this.cascade.length-1]
                //  为当前分类的等级赋值
                this.classifyForm.cat_level = this.cascade.length
                return
            } else {
                this.classifyForm.cat_pid = 0
                this.classifyForm.cat_level = 0
            
            }
        },


        //  点击按钮添加新的分类
         addCate(){
            this.$refs.classifyRef.validate( async valid => {
                if(!valid) return
                const {data:res} = await this.$http.post('categories',this.classifyForm)
                if(res.meta.status!==201){
               return this.$message.error('添加分类失败')
             }
                this.$message.success('添加分类成功')
                this.getCateList()
                this.classifyPop = false
            })                     
        },


        // 关闭清空弹框内容
        addCateClose(){

            
            this.$refs.classifyRef.resetFields()
            this.cascade = {}
            this.cascade.cat_pid = 0
            this.cascade.cat_level = 0
       
        },


        // 删除分类事件
        async deleteCataPop(id){
            const deleteData = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
             type: 'warning',        
        }).catch(err=>err)
 
           if(deleteData !== 'confirm') {
           return this.$message.info('已取消删除')
        } 
           const {data:res} = await this.$http.delete('categories/'+id)
           if(res.meta.status !==200){
               return this.$message.error('删除分类失败！')
           }
           this.$message.success('删除分类成功！')
            this.getCateList()
            this.classifyPop = false        
        } ,


        // 查找分类
        async editCatePop(id){
           const {data:res} = await this.$http.get('categories/'+id)
           this.editCateForm = res.data
           this.editCateVisible = true          
        },


        // 确认修改分类事件
        async daaEditPop(id){
            const {data:res} = await this.$http.put('categories/'+this.editCateForm.cat_id,{
                cat_name:this.editCateForm.cat_name
            })
            console.log(res);
            
            if(res.meta.status !==200){
                return this.$message.error('修改分类失败')
            }
            this.$message.success('修改分类成功！')
            this.getCateList()
            this.editCateVisible =false
        }

        



        }
    }


    

</script>

<style lang="less" scoped>
.cateBtn {
    margin-bottom: 15px;
}

.el-cascader {
    width: 100%;
}

</style>